#!/usr/bin/perl -w

BEGIN   {
	sub getPoints{return '../../' if (!$_[1]); return '../' if (!$_[0]); return '/';}
	(my $file = __FILE__) =~ s/(\/?modules)?(\/?http_logging)?\/?\w+\.pl$/&getPoints($1,$2)/e;
	$file = './' if $file eq '/'; #$file .= "bin";
    unshift(@INC, $file.'bin');
    unshift(@INC, $file.'modules/http_logging');
}

use strict;
use TWM;
use Logging;
use Data::Dumper;

my $logging = new Logging;
$logging->getCurrentSquidPort();
my ($add_rules, $delete_rules) = ('I', 'D');
my @ips;
if ($#ARGV > -1)
{
	$add_rules = $ARGV[0]=~/([AI])/?$ARGV[0]:'';
	$delete_rules = $ARGV[0]=~/([D])/?$ARGV[0]:'';
	shift @ARGV;
	@ips = @ARGV;
}


if ( ! -e "$ck{twmfolder}modules/$mc/conf/list.txt" )
{
	overwriteFile("$ck{twmfolder}modules/$mc/conf/list.txt",'');
}

my $xml = readModuleConfigFile($cm{ignore_ip});
$xml->{'pc'} = ref $xml->{'pc'} eq 'HASH'?[$xml->{'pc'}]:$xml->{'pc'};
my $ignore_ips = {};
$ignore_ips->{$_->{ip}} = 1 foreach (@{$xml->{'pc'}});

if ($#ips > -1)
{
	if ($delete_rules)
	{
		for (@ips)
		{
			$logging->runRules($delete_rules, $_);
		}
	}
	if ($add_rules)
	{
		for (@ips)
		{
			$logging->runRules($add_rules, $_) if !exists($ignore_ips->{$_});
		}
		append2File("$ck{twmfolder}modules/$mc/conf/list.txt", join("\n",@ips)."\n");
	}
}
else
{
	open(FILE, "+<$ck{twmfolder}modules/$mc/conf/list.txt") || die "Can't open $ck{twmfolder}modules/$mc/conf/list.txt $!\n";
	if ($delete_rules)
	{
		while (<FILE>)
		{
			chomp;
			next if !$_;
			$logging->runRules($delete_rules, $_);
		}
	}
	seek(FILE,0,0) || die "Seeking: $!\n";
	if ($add_rules)
	{
		my $ips = &getIPs;
		for (@$ips)
		{
			if ($_->{enabled})
			{
				print FILE "$_->{ip}\n";
				$logging->runRules($add_rules, $_->{ip}) if !exists($ignore_ips->{$_->{ip}});
			}
		}
	}
	truncate(FILE, tell(FILE)) || die "Truncating: $!\n";
	close FILE;
}

__END__
